var redis = require('redis');
var redisClient = redis.createClient();
var config = require('./../config.json');

module.exports = (function() {
    var express = require('express');
    var router = express.Router();
    var request = require('request');
    router.get('/:forceRefresh?', function(req, res) {
        var url = config.apiUrl;
        var forceRefresh = req.params.forceRefresh;
        console.log("force projects in redis Refresh is %s", !forceRefresh ? 'false' : 'true');
        if (forceRefresh) {
            redisClient.del("metroProjects:projects", function(req, reply) {
                console.log(reply);
                getProjects();
            });
        } else {
            getProjects();
        }

        function getProjects() {
            redisClient.get("metroProjects:projects", (function(req, res) {
                return function(err, reply) {
                    if (!reply) {
                        request({
                            url: url + '/projects/'
                        }, function(error, response, body) {
                            if (!error && response.statusCode == 200) {
                                redisClient.set("metroProjects:projects", body, redis.print);
                                res.send(JSON.parse(body));
                            } else {
                                res.send('fail to load!');
                            }
                        });
                    } else {
                        // reply = JSON.parse(reply);
                        res.send(JSON.parse(reply));
                    }
                    // redisClient.quit();
                };
            })(req, res));
        }
    });
    return router;
})();
